package com.beifu.manager.api.controller.login;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.beifu.manager.api.domain.baseInfo.AssetTypeInfoResponse;
import com.beifu.manager.api.domain.baseInfo.OrganizerInfoResponse;
import com.beifu.manager.api.domain.baseInfo.TrainInfoResponse;
import com.beifu.manager.dao.AssetTypeMapper;
import com.beifu.manager.dao.OrganizerMapper;
import com.beifu.manager.dao.TrainInfoMapper;
import com.beifu.manager.model.AssetType;
import com.beifu.manager.model.Organizer;
import com.beifu.manager.model.TrainInfo;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.beifu.manager.api.domain.logon.MobileModule;
import com.beifu.manager.api.domain.logon.MobileUserInfo;
import com.beifu.manager.api.domain.logon.MobileUserInfoResponse;
import com.beifu.manager.api.token.UserPassAuthenticationToken;
import com.beifu.manager.model.Module;
import com.utils.Constants;
import com.utils.ResponseHelp;

import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

/**
 * 接口查询菜单权限功能
 * Created by 再壮 on 2018/6/12.
 */
@RestController
@RequestMapping(value="/login/api", produces = "application/json;charset=UTF-8")
public class LoginQueryController {
    
	private Logger Log = Logger.getLogger(this.getClass());

	@Autowired
	private TrainInfoMapper trainInfoMapper;

	@Autowired
	private OrganizerMapper organizerMapper;

	@Autowired
	private AssetTypeMapper assetTypeMapper;
	
	/**
     * 登录 返回给 接口 该用户有权限查看的模块
     */
    @RequestMapping(value="/login")
    public String uploadSparesInWarehouse(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        
        
        if(JSONUtils.isNull(jsonIn)){
        	return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }
        if (null == jsonIn.get("loginName")) {
            return ResponseHelp.responseApiErrorText("1111", "用户名不能为空！");
        }
        if (null == jsonIn.get("password")) {
            return ResponseHelp.responseApiErrorText("1111", "密码不能为空！");
        }

        
        UserPassAuthenticationToken userPassAuthenticationToken = new UserPassAuthenticationToken(jsonIn.get("loginName").toString(),jsonIn.get("password").toString());
        
        Subject subject = SecurityUtils.getSubject();
        
		try {
			subject.login(userPassAuthenticationToken);// 验证角色和权限
		} catch (UnknownAccountException e) {
			Log.info("======账户不存在！");
			return ResponseHelp.responseApiErrorText(Constants.ErrorMessage.RETCODE0000001.getRetCode()
															, Constants.ErrorMessage.RETCODE0000001.getRetMsg());
		} catch (IncorrectCredentialsException e) {
			Log.info("======密码不匹配！");
			return ResponseHelp.responseApiErrorText(Constants.ErrorMessage.RETCODE0000002.getRetCode()
															, Constants.ErrorMessage.RETCODE0000002.getRetMsg());
		} catch (NullPointerException e) {
			Log.info("======用户名或密码不能为空！");
			return ResponseHelp.responseApiErrorText(Constants.ErrorMessage.RETCODE0000003.getRetCode()
															, Constants.ErrorMessage.RETCODE0000003.getRetMsg());
		}catch (LockedAccountException e) {
			Log.info("======账户已锁定！");
			return ResponseHelp.responseApiErrorText(Constants.ErrorMessage.RETCODE0000004.getRetCode()
															, Constants.ErrorMessage.RETCODE0000004.getRetMsg());
		}
        
		MobileUserInfo mobileUserInfo = (MobileUserInfo)subject.getPrincipal();
		String userId = mobileUserInfo.getUserId();
		String userName = mobileUserInfo.getUserName();
		List<Module> moduleList = mobileUserInfo.getModuleList();
		String mobileCookie = (String)subject.getSession().getId();

		//查询火车信息
		List<TrainInfo> trainInfos = trainInfoMapper.selectByExample(null);
		//查询组织信息
		List<Organizer> organizerList = organizerMapper.selectByExample(null);
		//查询资产类型信息
		List<AssetType> assetTypeList = assetTypeMapper.selectByExample(null);


		MobileUserInfoResponse mobileUserInfoResponse = new MobileUserInfoResponse();
		mobileUserInfoResponse.setUserId(userId);
		mobileUserInfoResponse.setUserName(userName);
		mobileUserInfoResponse.setModuleList(getMobileModuleList(moduleList));
		mobileUserInfoResponse.setMobileCookie("JSESSIONID="+mobileCookie);
		mobileUserInfoResponse.setOrganizeName(mobileUserInfo.getOrganizeName());
		mobileUserInfoResponse.setOrganizeType(mobileUserInfo.getOrganizeType());
		mobileUserInfoResponse.setOrganizeTypeName(mobileUserInfo.getOrganizeTypeName());
		mobileUserInfoResponse.setTrainInfoList(getTrainInfoResponseList(trainInfos));
		mobileUserInfoResponse.setOrganizerInfoList(getOrganizerInfoResponseList(organizerList));
		mobileUserInfoResponse.setAssetTypeInfoList(getAssetTypeInfoResponseList(assetTypeList));

        return ResponseHelp.responseApiSuccessText(mobileUserInfoResponse);
    }

    private List<AssetTypeInfoResponse> getAssetTypeInfoResponseList(List<AssetType> assetTypeList){
		List<AssetTypeInfoResponse> result = new ArrayList<AssetTypeInfoResponse>();
		if(null != assetTypeList && assetTypeList.size() > 0){
			for(AssetType assetType : assetTypeList){
				AssetTypeInfoResponse assetTypeInfoResponse = new AssetTypeInfoResponse();
				assetTypeInfoResponse.setId(assetType.getId());
				assetTypeInfoResponse.setModelName(assetType.getModelName());
				assetTypeInfoResponse.setName(assetType.getName());
				result.add(assetTypeInfoResponse);
			}
		}
    	return result;
	}

    private List<OrganizerInfoResponse> getOrganizerInfoResponseList(List<Organizer> organizerList){
		List<OrganizerInfoResponse> result = new ArrayList<OrganizerInfoResponse>();
		if(null != organizerList && organizerList.size() > 0){
			for(Organizer organizer : organizerList){
				OrganizerInfoResponse organizerInfoResponse = new OrganizerInfoResponse();
				organizerInfoResponse.setId(organizer.getId());
				organizerInfoResponse.setOrganizeName(organizer.getOrganizeName());
				organizerInfoResponse.setOrganizeType(organizer.getOrganizeType());
				organizerInfoResponse.setOrganizeTypeName(Constants.ORGANIZER_TYPE_enum.codeOf(organizer.getOrganizeType()+"").getName());
				result.add(organizerInfoResponse);
			}
		}
		return result;
	}

    private List<TrainInfoResponse> getTrainInfoResponseList(List<TrainInfo> trainInfos){
		List<TrainInfoResponse> result = new ArrayList<TrainInfoResponse>();
    	if(null != trainInfos && trainInfos.size() > 0){
    		for(TrainInfo trainInfo : trainInfos){
				TrainInfoResponse trainInfoResponse = new TrainInfoResponse();
				trainInfoResponse.setId(trainInfo.getId());
				trainInfoResponse.setTrainNo(trainInfo.getTrainNo());
				trainInfoResponse.setTrainNumber(trainInfo.getTrainNumber());
				result.add(trainInfoResponse);
			}
		}
    	return result;
	}


    private List<MobileModule> getMobileModuleList(List<Module> moduleList){
    	List<MobileModule> mobileModuleList = new ArrayList<MobileModule>();
    	if(null != moduleList && moduleList.size() > 0){
    		for(Module module : moduleList){
    			MobileModule mobileModule = new MobileModule();
    			mobileModule.setModuleName(module.getModuleName());
    			mobileModule.setModulePath(module.getModulePath());
    			mobileModuleList.add(mobileModule);
    		}
    	}
    	return mobileModuleList;
    }
    

}
